<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-select v-if="false" v-model="listQuery.lineNumber" :placeholder="$t('equipment.lineNumber')" class="filter-item" style="width: 200px" @change="handleLineSelect">
        <el-option v-for="item in lineOptions" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
      </el-select> -->
      <el-select v-model="listQuery.processNumber" :placeholder="$t('equipment.processNumber')" class="filter-item" clearable="" style="width: 350px;" @change="handleFilter">
        <el-option v-for="process in processOptions" :key="process.processNumber" :label="process.processName+'_'+process.processNumber" :value="process.processNumber" />
      </el-select>
      <el-input v-model="listQuery.resultCode" clearable :placeholder="$t('equipment.resultCode')" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('common.creatNew') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button>
      <el-button
        v-if="editRight"
        v-waves
        class="filter-item"
        type="warning"
        icon="el-icon-download"
        @click="handleProcess"
      >
        {{ $t('equipment.downloadProcess') }}
      </el-button>
    </div>
    <!-- 主界面数据 -->
    <el-table
      ref="dragTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      :row-style="{height:'20px'}"
      :cell-style="{padding:'2px'}"
      border
      fit
      row-key="id"
      highlight-current-row
      style="width: 100%;padding:1"
    >
      <el-table-column :label="$t('equipment.resultCode')" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.resultCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.resultName')" width="180px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.resultName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.resultUnit')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.resultUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.processName')" width="200PX" align="center">
        <template slot-scope="{row}">
          <span>{{ row.processName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.processNumber')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.processNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.colSetVersion')" width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.colSetVersion }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.charSeqNum')" width="140px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.charSeqNum }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.unitCount')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.unitCount }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.valueCount')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.valueCount }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.colSetId')" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.colSetId }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.targetValue')" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.targetValue }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.upperSpecLimit')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.upperSpecLimit }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.lowerSpecLimit')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.lowerSpecLimit }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.manualAutoMode')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.manualAutoMode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" width="150px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新建和更新对话框 -->
    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('equipment.processName')" required prop="processId">
          <el-select v-model="temp.processNumber" :placeholder="$t('equipment.processName')" class="filter-item" style="width: 450px">
            <el-option v-for="item in processOptions" :key="item.processNumber" :label="item.processName+'_'+item.processNumber" :value="item.processNumber" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('equipment.resultCode')" required prop="resultCode">
          <el-input v-model="temp.resultCode" :placeholder="$t('equipment.resultCode')" />
        </el-form-item>
        <el-form-item :label="$t('equipment.resultName')" required prop="resultName">
          <el-input v-model="temp.resultName" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.resultUnit')">
          <el-input v-model="temp.resultUnit" clearable />
        </el-form-item>
        <!-- <el-form-item :label="$t('equipment.processNumber')">
          <el-input v-model="temp.processNumber" clearable />
        </el-form-item> -->
        <el-form-item :label="$t('equipment.colSetVersion')">
          <el-input v-model="temp.colSetVersion" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.charSeqNum')">
          <el-input v-model="temp.charSeqNum" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.unitCount')">
          <el-input v-model="temp.unitCount" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.colSetId')">
          <el-input v-model="temp.colSetId" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.targetValue')">
          <el-input v-model="temp.targetValue" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.upperSpecLimit')">
          <el-input v-model="temp.upperSpecLimit" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.lowerSpecLimit')">
          <el-input v-model="temp.lowerSpecLimit" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.manualAutoMode')">
          <el-input v-model="temp.manualAutoMode" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 点击下载弹窗 -->
    <el-dialog :title="$t('equipment.downloadProcess')" :visible.sync="dialogForm" class="diag">
      <div style="display:flex">
        <el-form ref="form" label-width="100px">
          <el-form-item :label="$t('order.orderCode')">
            <el-radio-group
              v-model="checkedCities"
              @change="radiochange"
            >
              <el-row>
                <el-col :span="24">
                  <el-radio v-for="(item,index) in orderList" :key="index" :label="item">{{ item }}</el-radio>
                </el-col>
              </el-row>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <el-form ref="form" label-width="150px">
          <el-form-item :label="$t('equipment.processNumber')">
            <el-radio-group
              v-model="checkedC"
              @change="radiochanges"
            >
              <el-row>
                <el-col :span="24">
                  <el-radio v-for="(item,index) in processOptions" :key="index" :label="item">{{ item.processName + '_' + item.processNumber }}</el-radio>
                </el-col>
              </el-row>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleDownloadProcess">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProcessList, getProcessResultList, creatProcessResult, updateProcessResult, deleteProcessResult, downloadUserProcessFromMes } from '@/api/equipment'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import i18n from '@/lang'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { getOrderList } from '@/api/order'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ProcessResultDef',
  components: {
    Pagination
  },
  directives: { waves, elDragDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      checkedCities: [],
      checkedC: [],
      dialogForm: false,
      editRight: true,
      tableKey: 0,
      orderList: [],
      list: [],
      downqury: {
        lineNumber: '',
        orderCode: '',
        processNumber: ''
      },
      processOptions: [],
      // 任务u状态
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        lineName: '',
        lineNumber: '',
        processNumber: '',
        resultCode: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+processNumber'
      },
      // showReviewer: false,
      // showRemark: false,
      temp: {
        processResultId: 0,
        processId: 0,
        resultCode: '',
        resultName: '',
        resultUnit: '',
        processName: '',
        processNumber: '',
        colSetId: '',
        colSetVersion: 0,
        charSeqNum: 0,
        unitCount: 0,
        valueCount: 0,
        targetValue: '',
        upperSpecLimit: 0,
        lowerSpecLimit: 0,
        manualAutoMode: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      // dialogPvVisible: false,
      // pvData: [],
      rules: {
        processId: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        resultCode: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        resultName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }]
      },
      downloadLoading: false
      // searchLoading: {
      //   director: false
      // },
      // searchDialogStatus: '',
      // searchDialogFormVisible: {
      //   director: false
      // }
    }
  },
  watch: {
    $route: {
      handler(val) {
        if (this.$route.query.lineNumber !== undefined && this.$route.query.processNumber !== undefined) {
          this.listQuery.lineNumber = this.$route.query.lineNumber
          // this.getLineOptions()
          this.getProcessOptions()
          this.listQuery.processNumber = this.$route.query.processNumber
          this.getList()
        }
      }
    }
  },
  created() {
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
    this.listQuery.lineNumber = this.$store.getters.lineNumber // this.$route.query.lineId
    this.getProcessOptions()
    this.listQuery.processNumber = this.$route.query.processNumber
    this.getList()
    this.getOrderLists()
  },
  methods: {
    // timestepToolTip(index) {
    //   return index + '%'
    // },
    // formatDateTime(date) {
    //   return date.substring(0, 10)
    // },
    radiochange(e) {
      this.downqury.orderCode = e
    },
    radiochanges(e) {
      this.downqury.processNumber = e.processNumber
    },
    // 下载工艺数据唤起弹窗
    handleProcess() {
      this.dialogForm = true
      this.checkedCities = []
      this.checkedC = []
      this.downqury.lineNumber = this.listQuery.lineNumber
      this.downqury.orderCode = ''
      this.downqury.processNumber = ''
    },
    // 从服务器下载数据
    handleDownloadProcess() {
      if (this.downqury.orderCode === '') {
        this.$message({
          type: 'warning',
          message: i18n.t('msg.CAN_NOT_BE_NULL')
        })
        return
      }
      this.$confirm(i18n.t('produce.downloadOrNot'), i18n.t('common.tip'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        downloadUserProcessFromMes(this.downqury).then(response => {
          this.getList()
          this.$message({
            type: 'success',
            message: i18n.t('msg.DOWNLOAD_SUCCESS')
          })
          this.listLoading = false
        })
      })
    },
    // 获取订单清单
    getOrderLists() {
      this.listLoading = true
      getOrderList(this.listQuery).then(response => {
        response.data.orders.forEach(v => {
          this.orderList.push(v.orderCode)
        })
        this.listLoading = false
      })
    },
    // 获取工艺流程选项
    getProcessOptions() {
      this.listLoading = true
      this.processOptions = []
      getProcessList(this.listQuery).then(response => {
        this.processOptions = response.data.processes
        this.listLoading = false
      })
    },
    // 判断线体ID是否为空
    isEmptyLineId: function() {
      var ret = (this.listQuery.lineNumber === undefined || this.listQuery.lineNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.NO_LINE_SELECTED'),
          type: 'success',
          duration: 2000
        })
      }
      return ret
    },
    // 获取清单
    getList() {
      if (this.isEmptyLineId() === false) {
        this.listLoading = true
        getProcessResultList(this.listQuery).then(response => {
          this.list = response.data.processResults
          this.total = response.data.total
          this.listLoading = false
        })
      }
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp.processResultId = 0
      this.temp.processId = this.processOptions.length > 0 ? this.processOptions[0].processId : ''
      this.processOptions.forEach(e => {
        if (e.processNumber === this.listQuery.processNumber) {
          this.temp.processId = e.processId
          return
        }
      })
      this.temp.resultCode = ''
      this.temp.resultName = ''
      this.temp.resultUnit = ''
      this.temp.processName = ''
      this.temp.processNumber = ''
      this.temp.colSetId = ''
      this.temp.colSetVersion = 0
      this.temp.charSeqNum = 0
      this.temp.unitCount = 0
      this.temp.valueCount = 0
      this.temp.targetValue = ''
      this.temp.upperSpecLimit = 0
      this.temp.lowerSpecLimit = 0
      this.temp.manualAutoMode = ''
    },
    // 新建一个数据
    handleCreate() {
      if (this.isEmptyLineId() === false) {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.processOptions.forEach(p => {
            if (p.processNumber === this.temp.processNumber) {
              this.temp.processName = p.processName
            }
          })
          creatProcessResult(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.processOptions.forEach(p => {
            if (p.processId === this.temp.processId) {
              this.temp.processName = p.processName
            }
          })
          updateProcessResult(this.temp).then(response => {
            const index = this.list.findIndex(v => v.processResultId === this.temp.processResultId)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
      this.getList()
    },
    // 删除数据库信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_INFO_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          deleteProcessResult(this.temp).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.DELET_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
          })
        })
        .catch(err => { console.error(err) })
      this.getList()
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          i18n.t('equipment.resultCode'),
          i18n.t('equipment.resultName'),
          i18n.t('equipment.resultUnit'),
          i18n.t('equipment.processName'),
          i18n.t('equipment.processNumber'),
          i18n.t('equipment.colSetVersion'),
          i18n.t('equipment.charSeqNum'),
          i18n.t('equipment.unitCount'),
          i18n.t('equipment.valueCount'),
          i18n.t('equipment.colSetId'),
          i18n.t('equipment.targetValue'),
          i18n.t('equipment.upperSpecLimit'),
          i18n.t('equipment.lowerSpecLimit'),
          i18n.t('equipment.manualAutoMode')]
        const filterVal = ['resultCode', 'resultName', 'resultUnit', 'processName', 'processNumber', 'colSetVersion', 'charSeqNum', 'unitCount', 'valueCount', 'colSetId', 'targetValue', 'upperSpecLimit', 'lowerSpecLimit', 'manualAutoMode']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '工艺结果定义' + parseTime(Date.now(), '{y}{m}{d}{h}{i}{s}')
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style lang="scss" scoped>
.diag{
::v-deep .el-col-24{
  width: 14%!important;
    line-height: 25px!important;
}
::v-deep .el-dialog{
  width: 40vw!important;
}
}
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
